<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cos</title>
</head>
<body>
<canvas id='myCanvas' width="600px" height="300px" style="width: 100%;background: #eeeeee;"></canvas>

<script>
    var canvas = document.getElementById('myCanvas');
    var cxt = canvas.getContext('2d');
    var height = canvas.height;
    var width = canvas.width;

    var dis = 10;
    var fs = 14;
    cxt.font = fs + "px songti";

    cxt.lineWidth = 1;
    //说明文字
    cxt.fillText('三角函数-余弦函数',dis,fs*1.5);
    cxt.fillText('y = cos(x)  x∈R',dis,fs*3);


    //x轴绘制
    cxt.moveTo(dis, height / 2);
    cxt.lineTo(width - dis, height / 2);
    cxt.moveTo(width - dis - 4, height / 2 - 2);
    cxt.lineTo(width - dis, height / 2);
    cxt.lineTo(width - dis - 4, height / 2 + 2);

    //锯尺高
    var chiL = 4;
    for (var x = 1; x <= 7; x++) {
        cxt.moveTo(dis + x * (width - 2 * dis) / 8, height / 2 - chiL)
        cxt.lineTo(dis + x * (width - 2 * dis) / 8, height / 2)


        if ((-4 + x )/2) {
            //    说明文字
            if ((-4+x)%2){
                cxt.fillText((-4 + x)+"π/2", dis + x * (width - 2 * dis) / 8, height / 2 - fs*0.5);
            } else{
                cxt.fillText((-4 + x)/2+"π", dis + x * (width - 2 * dis) / 8, height / 2 + fs*1.5);
            }

        }
    }

    //y轴绘制
    cxt.moveTo(width / 2 - 2, dis + 4);
    cxt.lineTo(width / 2, dis);
    cxt.lineTo(width / 2 + 2, dis + 4);
    cxt.moveTo(width / 2, dis);
    cxt.lineTo(width / 2, height - dis - 4);

    for (var y = 1; y <= 5; y++) {
        cxt.moveTo(width / 2, dis + y * (height - 2 * dis) / 6);
        cxt.lineTo(width / 2 + chiL, dis + y * (height - 2 * dis) / 6);

        if (2 - y + 1) {
            //    说明文字
            cxt.fillText('' + (2 - y + 1), width / 2 + chiL + 0.5*fs, dis + y * (height - 2 * dis) / 6);
        }
    }


    cxt.stroke();

    //标注文字

    cxt.fillText('y', width / 2 - fs, dis + fs);
    cxt.fillText('x', width - dis - fs, height / 2 + fs);
    cxt.fillText('o', width / 2 - fs, height / 2 + fs);

    var l = 2 * Math.PI;
    var cosv = 0;
    var cosX = 0;
    var cosY = 0;

    for (var i = -360; i <= 360; i++) {
        cosv = Math.cos(l * i / 360);
        //x轴长4pi
        cosX = dis + (i + 360) * (width - 2 * dis) / 720;
        cosY = height / 2 - cosv * (height - 2 * dis) / 6;
        if (i === -360) {
            cxt.moveTo(cosX, cosY);
            continue;
        }
        cxt.lineTo(cosX, cosY);
        //说明文字,

    }
    cxt.stroke()
</script>
</body>
</html>